<template>
  <view class="address-selector">
    <!-- 地址选择触发区域 -->
    <view class="address-trigger" @click="openAddressModal" v-if="!isIndependent">
      <slot name="trigger">
        <view class="default-trigger">
          <view class="trigger-header" v-if="selectedAddress">
            <text class="name">{{ selectedAddress.userName }}</text>
            <text class="phone">{{ selectedAddress.telNumber }}</text>
          </view>
          <view class="trigger-address" v-if="selectedAddress">
            {{ formatAddress(selectedAddress) }}
          </view>
          <view class="no-address" v-else>
            <u-icon name="location" size="28" color="#999"></u-icon>
            <text class="no-address-text">请选择收货地址</text>
          </view>
        </view>
      </slot>
    </view>

    <!-- 地址选择弹窗 -->
    <u-modal
        v-model="showModal"
        title="选择收货地址"
        :mask-close-able="false"
        :confirm-btn="false"
        :cancel-btn="false"
        :height="isIndependent ? '100%' : '80%'"
        :round="16"
    >
      <!-- 新增地址按钮 -->
      <view class="add-address-btn" @click="navigateToAddAddress">
        <u-icon name="plus" size="28" color="#ff4500"></u-icon>
        <text class="add-address-text">新增收货地址</text>
      </view>

      <!-- 地址列表 -->
      <view class="address-list">
        <view v-if="addressList.length === 0" class="empty-address">
          <u-icon name="location" size="60" color="#ccc"></u-icon>
          <text class="empty-text">暂无收货地址</text>
        </view>

        <view
            class="address-item"
            v-for="(address, index) in addressList"
            :key="address.id"
            @click="selectThisAddress(address)"
        >
          <!-- 地址信息 -->
          <view class="address-content">
            <view class="address-header">
              <text class="address-name">{{ address.userName }}</text>
              <text class="address-phone">{{ address.telNumber }}</text>
              <u-icon
                  name="edit-pen"
                  size="24"
                  color="#666"
                  class="edit-icon"
                  @click.stop="editAddress(address)"
              ></u-icon>
            </view>
            <view class="address-detail">
              {{ formatAddress(address) }}
            </view>
          </view>

          <!-- 默认地址标签和选中状态 -->
          <view class="address-footer">
            <u-tag
                text="默认地址"
                size="mini"
                shape="circle"
                color="#ff4500"
                v-if="address.isDefault"
            ></u-tag>
            <u-icon
                name="checkmark-circle"
                size="28"
                color="#ff4500"
                v-if="selectedAddress && selectedAddress.id === address.id"
            ></u-icon>
          </view>
        </view>
      </view>

      <!-- 独立页面模式的关闭按钮 -->
      <view
          class="close-btn"
          @click="closeModal"
          v-if="isIndependent"
      >
        <u-icon name="close" size="32" color="#666"></u-icon>
      </view>
    </u-modal>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, defineProps, defineEmits } from 'vue';
import { useRoute, useRouter } from 'vue-router';

// 组件属性
const props = defineProps({
  // 是否为独立页面模式（全屏显示）
  isIndependent: {
    type: Boolean,
    default: false
  },
  // 已选中的地址
  modelValue: {
    type: Object,
    default: null
  },
  // 是否允许编辑地址
  allowEdit: {
    type: Boolean,
    default: true
  }
});

// 组件事件
const emit = defineEmits(['update:modelValue', 'addressSelected']);

// 状态管理
const showModal = ref(false);
const addressList = ref([]);
const selectedAddress = ref(props.modelValue);
const route = useRoute();
const router = useRouter();

// 监听外部传入的地址变化
watch(
    () => props.modelValue,
    (newVal) => {
      selectedAddress.value = newVal;
    },
    { deep: true }
);

// 初始化
onMounted(() => {
  // 独立页面模式下直接打开弹窗
  if (props.isIndependent) {
    showModal.value = true;
  }
  // 获取地址列表
  fetchAddressList();

  // 监听地址编辑返回
  uni.$on('addressUpdated', () => {
    fetchAddressList();
  });
});

// 打开地址选择弹窗
const openAddressModal = () => {
  showModal.value = true;
  fetchAddressList();
};

// 关闭弹窗
const closeModal = () => {
  showModal.value = false;
  if (props.isIndependent) {
    router.back();
  }
};

// 获取地址列表
const fetchAddressList = () => {
  // 实际项目中替换为真实接口请求
  setTimeout(() => {
    // 模拟地址数据
    addressList.value = [
      {
        id: '1',
        userName: '张三',
        telNumber: '13800138000',
        provinceName: '广东省',
        cityName: '深圳市',
        countyName: '南山区',
        detailInfo: '科技园南区10栋501',
        isDefault: true
      },
      {
        id: '2',
        userName: '李四',
        telNumber: '13900139000',
        provinceName: '北京市',
        cityName: '北京市',
        countyName: '海淀区',
        detailInfo: '中关村大街1号',
        isDefault: false
      }
    ];

    // 如果没有选中地址，默认选择默认地址
    if (!selectedAddress.value && addressList.value.length > 0) {
      selectedAddress.value = addressList.value.find(item => item.isDefault) || addressList.value[0];
    }
  }, 300);
};

// 格式化地址显示
const formatAddress = (address) => {
  return `${address.provinceName}${address.cityName}${address.countyName}${address.detailInfo}`;
};

// 选择当前地址
const selectThisAddress = (address) => {
  selectedAddress.value = address;
  emit('update:modelValue', address);
  emit('addressSelected', address);

  if (!props.isIndependent) {
    showModal.value = false;
  } else {
    router.back();
  }
};

// 跳转到新增地址页面
const navigateToAddAddress = () => {
  router.push({
    path: '/pages/address/add-address',
    query: {
      from: 'address-selector'
    }
  });
};

// 编辑地址
const editAddress = (address) => {
  router.push({
    path: '/pages/address/edit-address',
    query: {
      addressId: address.id,
      from: 'address-selector'
    }
  });
};

// 组件销毁时清理事件监听
onUnmounted(() => {
  uni.$off('addressUpdated');
});
</script>

<style scoped>
/* 触发区域样式 */
.address-trigger {
  width: 100%;
}

.default-trigger {
  padding: 20rpx 0;
}

.trigger-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.name, .phone {
  font-size: 30rpx;
  color: #333;
}

.trigger-address {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.no-address {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  color: #999;
}

.no-address-text {
  font-size: 30rpx;
  margin-left: 10rpx;
}

/* 弹窗内样式 */
.add-address-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 90rpx;
  border: 1rpx dashed #ddd;
  border-radius: 8rpx;
  margin: 20rpx;
  color: #ff4500;
}

.add-address-text {
  font-size: 30rpx;
  margin-left: 10rpx;
}

.address-list {
  max-height: calc(100% - 130rpx);
  overflow-y: auto;
  padding-bottom: 20rpx;
}

.address-item {
  padding: 25rpx 20rpx;
  margin: 0 20rpx 15rpx;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  position: relative;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.address-name {
  font-size: 30rpx;
  color: #333;
  margin-right: 20rpx;
}

.address-phone {
  font-size: 30rpx;
  color: #333;
  flex: 1;
  text-align: right;
}

.edit-icon {
  margin-left: 15rpx;
}

.address-detail {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 15rpx;
}

.address-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.empty-address {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
  margin-top: 20rpx;
}

.close-btn {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  z-index: 99;
}
</style>